<template>
  <div class="dictionary">
    <el-row class="search-bar" type="flex" justify="space-between" align="middle">
      <el-col :span="8">
        <el-input v-model="searchQuery" placeholder="搜索..." style="width: 100%;"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="searchDictionaries">搜索</el-button>
      </el-col>
      <el-col :span="4">
        <el-button type="success" @click="openAddParentDialog">新增父类</el-button>
      </el-col>
    </el-row>
    <el-table :data="dictionaries" stripe style="width: 100%; margin-top: 20px;" height="565px" @row-dblclick="openEditChildDialog">
      <el-table-column prop="name" label="父类名称" width="180"></el-table-column>
      <el-table-column prop="code" label="编码" width="180"></el-table-column>
      <el-table-column prop="sort" label="排序" width="100"></el-table-column>
      <el-table-column prop="createdBy" label="创建人" width="180"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.createdAt | formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="deleteParent(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
        style="margin-top: 20px;"
    ></el-pagination>

    <!-- 新增父类弹窗 -->
    <el-dialog title="新增父类" :visible.sync="isAddParentDialogOpen" width="50%" center>
      <el-form label-position="top" :model="newParent" ref="newParentForm" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="父类名称" prop="name">
              <el-input v-model="newParent.name" placeholder="父类名称" required></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编码" prop="code">
              <el-input v-model="newParent.code" placeholder="编码" required></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="newParent.sort" placeholder="排序" required></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddParentDialog">取 消</el-button>
        <el-button type="primary" @click="addParent">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑子类弹窗 -->
    <el-dialog title="编辑子类" :visible.sync="isEditChildDialogOpen" width="50%" center>
      <div>
        <h3>新增子类</h3>
        <el-form label-position="top" :model="newChild" ref="newChildForm" :rules="rules">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="子类名称" prop="name">
                <el-input v-model="newChild.name" placeholder="子类名称" required></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="编码" prop="code">
                <el-input v-model="newChild.code" placeholder="编码" required></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排序" prop="sort">
                <el-input v-model="newChild.sort" placeholder="排序" required></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="父类" prop="parentCode">
                <el-input v-model="newChild.parentCode" placeholder="父类编码" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button type="primary" @click="addChild" style="margin-top: 20px;">确 定</el-button>
        <el-button @click="clearNewChild" style="margin-top: 20px;">清 空</el-button>
      </div>
      <div style="margin-top: 20px;">
        <h3>展示子类</h3>
        <el-table :data="currentParentData" stripe style="width: 100%; margin-top: 20px;">
          <el-table-column prop="name" label="子类名称" width="180"></el-table-column>
          <el-table-column prop="code" label="编码" width="180"></el-table-column>
          <el-table-column prop="sort" label="排序" width="120"></el-table-column>
          <el-table-column prop="createdBy" label="创建人" width="180"></el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.createdAt | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="editChild(scope.$index)">编辑</el-button>
              <el-button type="danger" size="mini" @click="deleteChild(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      searchQuery: '',
      dictionaries: [],
      isAddParentDialogOpen: false,
      newParent: { name: '', code: '', sort: '' },
      isEditChildDialogOpen: false,
      newChild: { name: '', code: '', sort: '', parentCode: '' },
      currentParent: {},
      currentParentData: [],
      editingChildIndex: -1,
      currentPage: 1,
      pageSize: 10,
      totalItems: 1,
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      }
    };
  },
  filters: {
    formatDate(dateStr) {
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }
  },
  computed: {
  },
  methods: {
    searchDictionaries() {
      this.fetchDictionaries();
    },
    openAddParentDialog() {
      this.isAddParentDialogOpen = true;
    },
    closeAddParentDialog() {
      this.isAddParentDialogOpen = false;
      this.$refs.newParentForm.resetFields();
    },
    addParent() {
      this.$refs.newParentForm.validate(valid => {
        if (valid) {
          this.$http.post('/api/dictionary/parent', this.newParent, {
            headers: {
              token: localStorage.getItem("token")
            }
          })
            .then(response => {
              if (response.status === 200) {
                // 更新表格数据
                this.fetchDictionaries()
                this.closeAddParentDialog();
                this.$message.success('操作成功')
              } else {
                this.$message.error('失败')
              }
            })
            .catch(error => {
              console.error('Error adding parent:', error);
              this.$message.error('失败' + error)
            });
        }
      });
    },
    openEditChildDialog(row) {
      this.currentParent = row;
      this.clearNewChild() // 每次点开清空上一次的数据
      this.currentParentDataList() // 执行查询
      this.newChild.parentCode = row.code; // 默认带入父类的编码
      this.isEditChildDialogOpen = true;
    },
    clearNewChild() {
      this.newChild = { name: '', code: '', sort: '', parentCode: this.currentParent.code };
    },
    addChild() {
      this.$refs.newChildForm.validate(valid => {
        if (valid) {
          this.$http.post(`/api/dictionary/parent`, this.newChild, {
            headers: {
              token: localStorage.getItem("token")
            }
          })
            .then(response => {
              if (response.status === 200) {
                // 执行一遍查询
                this.currentParentDataList()
                this.clearNewChild();
                this.$message.success('操作成功')
              } else {
                this.$message.error('失败')
              }
            })
            .catch(error => {
              console.error('Error adding child:', error);
              this.$message.error('失败' + error)
            });
        }
      });
    },
    editChild(index) {
      this.editingChildIndex = index;
      this.newChild = { ...this.currentParent.children[index] };
    },
    deleteChild(index) {
      this.$confirm('此操作将永久删除该子类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const childId = this.currentParent.children[index].id;
        this.$http.delete(`/api/dictionary/${childId}`, {
          headers: {
            token: localStorage.getItem("token")
          }
        })
          .then((res) => {
            if (res.status === 200) {
              this.currentParent.children.splice(index, 1);
              this.$message.success('操作成功')
            } else {
              this.$message.error('失败')
            }
          })
          .catch(error => {
            console.error('Error deleting child:', error);
            this.$message.error('失败' + error)
          });
      }).catch(() => {
        // 取消删除
      });
    },
    deleteParent(row) {
      this.$confirm('此操作将永久删除该父类及其所有子类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/api/dictionary/${row.id}`, {
          headers: {
            token: localStorage.getItem("token")
          }
        })
          .then((res) => {
            if (res.status === 200) {
              this.fetchDictionaries()
              this.$message.success('操作成功')
            } else {
              this.$message.error('失败')
            }
          })
          .catch(error => {
            console.error('Error deleting parent:', error);
            this.$message.error('失败' + error)
          });
      }).catch(() => {
        // 取消删除
      });
    },
    fetchDictionaries() {
      this.$http.get('/api/dictionary/by-parent-code', {
        headers: {
          token: localStorage.getItem("token")
        },
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(response => {
        console.log(response)
        this.dictionaries = response.data.records;
        this.totalItems = response.data.total;
      }).catch(error => {
        console.error('Error fetching dictionaries:', error);
        this.$message.error('失败' + error)
      });
    },
    currentParentDataList() {
      this.$http.get('/api/dictionary/by-parent-code', {
        headers: {
          token: localStorage.getItem("token")
        },
        params: {
          parentCode: this.currentParent.code
        }
      }).then(response => {
        console.log(response);
        this.currentParentData = response.data.records;
        // 确保 currentParent 有 children 属性
        this.currentParent.children = response.data.records || [];
      }).catch(error => {
        console.error('Error fetching dictionaries:', error);
        this.$message.error('失败' + error)
      });
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchDictionaries()
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchDictionaries()
    }
  },
  created() {
    this.fetchDictionaries();
  }
};
</script>

<style scoped>
.dictionary {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-bar {
  margin-bottom: 20px;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  display: flex;
  align-items: center;
}

.el-input {
  margin-right: 10px;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #409eff;
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  padding: 15px;
}
</style>
